package com.android.webframework;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.os.Environment;

public class MP3Service extends HTTPService {
	protected RequestObject requestOb;
	private File mp3Loc;
	
	public static int fileNo = 0;
	
	/**
	 * Argument MP3Framework constructor
	 * @param requestOb takes in a request object
	 */
	public MP3Service(RequestObject requestOb) {
		servicesLog.setLogTag("MP3Svc");
		this.requestOb = requestOb;
		fileNo++;
	}
	
	/**
	 * Request a service
	 * @return a response object
	 * @see ResponseObject
	 */
	public ResponseObject request() throws RequestException {
		try {
			String fileName = "mp3file" + fileNo + ".mp3";
			mp3Loc = new File(Environment.getExternalStorageDirectory(), fileName);

			servicesLog.appendToLog("File connecion established");
			
			FileOutputStream f = new FileOutputStream(mp3Loc);
			
			servicesLog.appendToLog("Local file open");
			
			InputStream in = requestHttp((String)requestOb.getParameter("url"));
			
			byte[] buffer = new byte[1024];
	        int len1 = 0;

	        while ((len1 = in.read(buffer)) > 0) {
	            f.write(buffer, 0, len1);
	        }
	        f.close();
	        servicesLog.appendToLog("Successfully downloaded file");
		}
		catch (ObjectNotFoundException onf) {
			onf.toString();
		}
		catch (Exception e) {
			servicesLog.appendToLog("File download failed. Error:" + e.getClass() + e.getMessage());
		}
		return new ResponseObject(mp3Loc);
	}
	
}
